# 定义过滤器 转换索引
import functools

from flask import g, session, current_app

from info.models import User

from io import BytesIO

from PIL import Image, ImageDraw, ImageFont
import random
import string

def index_filter(index):
    if index == 0:
        return 'first'
    elif index == 1:
        return 'second'
    elif index == 2:
        return 'third'
    else:
        return ''



# 查询登录信息
def user_login_data(f):  # f = news_detail

    @functools.wraps(f)  # 该装饰器可以让闭包使用指定函数的信息(如函数名f.__name__ 函数文档注释f.__doc__)
    def wrapper(*args, **kwargs):
        # 判断用户是否登录  `从session中取userid`
        user_id = session.get("user_id")
        user = None
        if user_id:  # 已登录
            # 根据userid取出用户信息
            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)

        g.user = user

        return f(*args, **kwargs)

    return wrapper


access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
bucket_name = "infonews"  # 存储空间名称


def img_upload(data):
    """
    上传图片
    :param data: 上传的文件
    :return:  生成的文件名
    """
    import qiniu


    q = qiniu.Auth(access_key, secret_key)
    key = None  # 文件名, 如果不设置, 会生成随机文件名
    token = q.upload_token(bucket_name)
    # 上传文件
    ret, info = qiniu.put_data(token, key, data)

    if ret is not None:
        return ret.get("key")  # 获取生成的随机文件名
    else:
        raise BaseException(info)



def generate_captcha_image(size=(30, 30), font_size=40, length=4,fmt='JPEG'):
    # 创建图像
    image = Image.new("RGB", size, "white")
    draw = ImageDraw.Draw(image)

    # 设置字体
    font = ImageFont.load_default()

    # 生成随机字符串
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))

    # 获取文本大小
    text_size = draw.textlength(captcha_text, font)

    # 在图像中心绘制文本
    text_position = ((size[0] - text_size) // 2, (size[1] - text_size) // 2)
    draw.text(text_position, captcha_text, font=font, fill="black")

    out = BytesIO()
    image.save(out, format=fmt)
    return captcha_text, out.getvalue()




